
import React, { createContext, useContext, useEffect, useState } from "react";
import { getEditorEnvironment } from "./EditorEnvContext";

type _Viewport = {
    width: number, height: number
}

const editorViewportContext = createContext<_Viewport>({width: window.innerWidth,
                                             height: window.innerHeight});

export default function ({children}) {
    const [width, setWidth] = useState(window.innerWidth);
    const [height, setHeight] = useState(window.innerWidth);

    const env = getEditorEnvironment();

    const handleWindowResize = () => {
        setWidth(window.innerWidth);
        setHeight(window.innerHeight);

        env.onEditorViewportChange(window.innerWidth, window.innerHeight);

        console.log('resize: ' + window.innerWidth + 'x' + window.innerHeight);
    }

    useEffect(() => {
        window.addEventListener('resize', handleWindowResize)
        setWidth(window.innerWidth);
        setHeight(window.innerHeight);
        
        return () => window.removeEventListener('resize', handleWindowResize);
    });

    return (
        <editorViewportContext.Provider value={{width: width, height: height}}>
            {children}
        </editorViewportContext.Provider>
    )
}

export function getEditorViewport(): _Viewport {
    return useContext(editorViewportContext);
}
